﻿using System;
using System.Reflection;

namespace ServiceKit
{
    /// <summary>
    /// 属性或参数最大长度
    /// </summary>
    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter)]
    public class MaxLengthAttribute : Attribute
    {

        /// <summary>
        /// 长度
        /// </summary>
        public int Lenght { get; set; }

        /// <summary>
        /// 属性或参数最大长度
        /// </summary>
        /// <param name="lenght"></param>
        public MaxLengthAttribute(int lenght)
        {
            this.Lenght = lenght;
        }
    }

    public static class ParameterInfoExtentions
    {

        /// <summary>
        /// 获取最大长度
        /// </summary>
        /// <param name="prperty"></param>
        /// <returns></returns>
        public static int GetMaxLenght(this PropertyInfo prperty)
        {
            var attrs = prperty.GetCustomAttributes(true);
            foreach (var obj in attrs)
            {
                var attr = obj as MaxLengthAttribute;
                if (attr != null) return (obj as MaxLengthAttribute).Lenght;
            }
            return 0;
        }

        /// <summary>
        /// 获取最大长度
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public static int GetMaxLenght(this ParameterInfo param)
        {
            var attrs = param.GetCustomAttributes(true);
            foreach (var obj in attrs)
            {
                var attr = obj as MaxLengthAttribute;
                if (attr != null) return (obj as MaxLengthAttribute).Lenght;
            }
            return 0;
        }

    }
}
